<template>
    <div class="topContainer" v-loading="topLoading">
        <el-card class="topContainerCard">
            <div style="display: flex; justify-content: space-between">
                <span>流程名称：{{currentFlowName}}</span>
                <div>
                    <div v-if="checkIsCanSave" style="display: inline-block;width: 240px; height: 30px; background-color: rgba(238,183,5,0.56);margin-right: 20px; text-align: center">
                        <span style="color: rgba(248,143,6,0.98); line-height: 30px">
                            历史版本只可查看，不可修改
                        </span>
                    </div>
                    <el-select v-model="currentVersion" placeholder="版本" style="width: 200px;margin-right: 10px" @change="selectChange()" >
                        <el-option
                            v-for="item in currentFlowVersionList"
                            :key="item.version"
                            :label="item.innerName"
                            :value="item.version"
                        />
                    </el-select>
                    <el-button type="success" :disabled="checkIsCanSave" @click="clickGlobalParam()">全局变量</el-button>
                    <el-button @click="closeCurrentPage()">关闭</el-button>
                    <el-button type="primary" :loading="saveFlowJsonLoading" :disabled="checkIsCanSave" @click="saveFlowJsonInfo()">保存</el-button>
                </div>
            </div>
        </el-card>
    </div>

    <div :style="'margin-top: 100px; width: ' + jsonInfo['maxWidth'] + 'px'">
        <component :is="jsonInfo['type']" :jsonInfo="jsonInfo" :globalJson="jsonInfo" :flowDetailJson="flowDetailJson"></component>
    </div>

    <el-drawer v-model="globalParamFlag" size="50%" title="全局流程配置" :with-header="false" :close-on-click-modal="false" :lock-scroll="true">
        <YwuGlobalParamDrawer :globalProperties="globalParamJsonInfo"/>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelUpdate()">取消</el-button>
                <el-button type="primary" @click="confirmUpdate()">确认</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup name="BuildFlow">
import {getMaxWidth, parseMultiInfo} from "@/utils/flowCommon";
import {queryFlowInfo, queryFlowVersionInfo, queryFlowVersionList, saveFlowJson} from "@/request/flow";
import {ElNotification} from "element-plus";
import {computed, onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import YwuGlobalParamDrawer from "@/views/bpmn/flow/drawer/YwuGlobalParamDrawer.vue";
import {deepCopy} from "@/utils/ywuCommon.js";

let route = useRoute();
let router = useRouter();

let jsonInfo = ref({});
let currentFlowName = ref("");
let currentVersion = ref(0);
let currentFlowVersionList = ref([]);
let saveFlowJsonLoading = ref(false);
let topLoading = ref(false);
let flowDetailJson = ref({});
let globalParamFlag = ref(false);
let globalParamJsonInfo = ref({})

let checkIsCanSave = computed(() => {
    if (currentFlowVersionList.value && currentFlowVersionList.value.length > 0) {
        // 如果当前表单存在草稿版本，那么只有草稿版本可以编辑，其他版本都不可以编辑
        if (currentFlowVersionList.value[0].version === 0) {
            return currentVersion.value !== 0;
        }
        // 如果当前表单不存在草稿版本，那么只有最新版本可以编辑，其他版本都不可以编辑
        return currentFlowVersionList.value[0].version !== currentVersion.value;
    } else {
        return true;
    }
})

onMounted(() => {
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
    parseMultiInfo(jsonInfo.value);
    getMaxWidth(jsonInfo.value);
})

function clickGlobalParam() {
    globalParamJsonInfo.value = deepCopy(jsonInfo.value.globalProperties)
    if (!globalParamJsonInfo.value.tableData) {
        globalParamJsonInfo.value.tableData = []
    }
    globalParamFlag.value = true;
}

function cancelUpdate() {
    globalParamJsonInfo.value = {}
    globalParamFlag.value = false;
}

function confirmUpdate() {
    jsonInfo.value.globalProperties = deepCopy(globalParamJsonInfo.value)
    globalParamJsonInfo.value = {}
    globalParamFlag.value = false;
}

init();
function init() {
    // 查询流程信息
    let currentFlowId = route.query.id;
    topLoading.value = true;
    // 查询版本列表
    queryFlowVersionList({id: currentFlowId}).then(res => {
        if (res.code === "200") {
            // 如果返回的list为空，则说明没有历史版本，只有草稿状态
            if (res.data.length === 0) {
                queryFlowInfo({id: currentFlowId}).then(queryRes => {
                    if (queryRes.code === "200") {
                        flowDetailJson.value = queryRes.data
                        let jsonStr = queryRes.data.flowJson
                        jsonInfo.value = JSON.parse(jsonStr)
                        currentFlowName.value = queryRes.data.nameCn + ' - ' + queryRes.data.nameEn;
                        if (!jsonInfo.value.globalProperties) {
                            jsonInfo.value.globalProperties = {}
                        }
                    }
                    currentVersion.value = 0
                    topLoading.value = false;
                }).catch(res => {
                    topLoading.value = false;
                })
                // 手动填充一个草稿版本的数据
                currentFlowVersionList.value.push({
                    innerName: "草稿版本",
                    version: 0
                })
            } else {
                for (let index = 0; index < res.data.length; index++) {
                    if (res.data[index].version === 0) {
                        res.data[index].innerName = "草稿版本";
                    } else {
                        res.data[index].innerName = "版本" + res.data[index].version;
                    }
                }
                currentFlowVersionList.value = res.data;
                // 如果当前url中携带了version，则说明当前是查询最新版本
                let queryVersion = route.query.version
                if (queryVersion !== null && queryVersion !== undefined) {
                    // 查询当前版本
                    queryFlowVersionInfo({version: queryVersion, resourceId: currentFlowId}).then(versionRes => {
                        if (versionRes.code === "200") {
                            flowDetailJson.value = versionRes.data
                            let jsonStr = versionRes.data.flowJson
                            jsonInfo.value = JSON.parse(jsonStr)
                            currentFlowName.value = versionRes.data.nameCn + ' - ' + versionRes.data.nameEn;
                            currentVersion.value = parseInt(queryVersion, 10);
                            if (!jsonInfo.value.globalProperties) {
                                jsonInfo.value.globalProperties = {}
                            }
                        }
                        topLoading.value = false;
                    }).catch(res => {
                        topLoading.value = false;
                    })
                } else {
                    // 查询最新版本
                    queryFlowVersionInfo({version: res.data[0].version, resourceId: currentFlowId}).then(versionRes => {
                        if (versionRes.code === "200") {
                            flowDetailJson.value = versionRes.data
                            let jsonStr = versionRes.data.flowJson
                            jsonInfo.value = JSON.parse(jsonStr)
                            currentFlowName.value = versionRes.data.nameCn + ' - ' + versionRes.data.nameEn;
                            currentVersion.value = res.data[0].version
                            if (!jsonInfo.value.globalProperties) {
                                jsonInfo.value.globalProperties = {}
                            }
                        }
                        topLoading.value = false;
                    }).catch(res => {
                        topLoading.value = false;
                    })
                }
            }
        }
    }).catch(res => {
        topLoading.value = false;
    })
}

function selectChange() {
    topLoading.value = true
    let currentFlowId = route.query.id;
    let currentQueryParams = route.query;
    router.replace({
        path: route.path,
        query: {
            id: currentQueryParams.id,
            version: currentVersion.value
        }
    })
    // 查询历史版本
    queryFlowVersionInfo({version: currentVersion.value, resourceId: currentFlowId}).then(versionRes => {
        if (versionRes.code === "200") {
            flowDetailJson.value = versionRes.data
            let jsonStr = versionRes.data.flowJson
            jsonInfo.value = JSON.parse(jsonStr)
            currentFlowName.value = versionRes.data.nameCn + ' - ' + versionRes.data.nameEn;
            if (!jsonInfo.value.globalProperties) {
                jsonInfo.value.globalProperties = {}
            }
        }
        topLoading.value = false;
    }).catch(res => {
        topLoading.value = false;
    })
}

function closeCurrentPage() {
    window.close();
}

function saveFlowJsonInfo() {
    let currentFlowId = route.query.id;
    saveFlowJsonLoading.value = true;
    // 保存json
    saveFlowJson({id: currentFlowId, flowJson: JSON.stringify(jsonInfo.value)}).then(res => {
        if (res.code === "200") {
            saveFlowJsonLoading.value = false;
            ElNotification({
                title: 'Success',
                message: res.message,
                type: 'success'
            })
            // 延迟一秒关闭页面
            setTimeout(() => {
                window.close();
            }, 1000);
        }
        saveFlowJsonLoading.value = false;
    }).catch(res => {
        saveFlowJsonLoading.value = false;
    })
}
</script>

<style scoped lang="less">
.topContainerCard {
    height: 68px;
    margin-top: 6px;
    margin-bottom: 6px;
    z-index: 10000;
}

.topContainer {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
}
</style>